<template>
  <div class="dashboard" v-if="isReady">
    <!-- 原有仪表盘内容 -->
    <header class="dashboard-header">
      <div class="header-left">
        <h1>仪表盘</h1>
      </div>
      <div class="header-right">
        <div class="user-menu" v-if="authStore.user">
          <!-- 用户菜单内容 -->
          <button class="user-button" @click="toggleMenu">
            <img :src="authStore.user.avatar || defaultAvatar" class="user-avatar">
            <span class="user-name">{{ authStore.user.username }}</span>
            <i class="fas fa-chevron-down transition-transform duration-300" :class="{ 'rotate-180': menuOpen }"></i>
          </button>
          <div v-if="menuOpen" class="dropdown-menu transform origin-top-right transition-all duration-300 ease-in-out opacity-0 scale-95"
               :class="{ 'opacity-100 scale-100': menuOpen }">
            <router-link to="/user-profile" class="dropdown-item">
              <i class="fas fa-user"></i> 用户资料
            </router-link>
            <router-link to="/settings" class="dropdown-item">
              <i class="fas fa-cog"></i> 设置
            </router-link>
            <div class="dropdown-divider"></div>
            <button class="dropdown-item" @click="handleLogout">
              <i class="fas fa-sign-out-alt"></i> 登出
            </button>
          </div>
        </div>
      </div>
    </header>

    <main class="dashboard-content">
      <div class="welcome-card" v-if="authStore.user">
        <div class="welcome-text">
          <h2>欢迎回来, {{ authStore.user.username }}!</h2>
          <p>今天是 {{ currentDate }}</p>
        </div>
        <div class="welcome-image">
          <img src="@/assets/welcome.svg" alt="Welcome">
        </div>
      </div>
    </main>
  </div>

  <!-- 加载状态 -->
  <div v-else-if="isLoading" class="loading-container">
    <el-icon class="is-loading"><Loading /></el-icon>
    <p>加载中...</p>
  </div>

  <!-- 未认证状态 -->
  <div v-else class="loading-container">
    <p>请先登录</p>
    <el-button type="primary" @click="router.push('/login')">前往登录</el-button>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import defaultAvatar from '@/assets/default-avatar.png'
import { Loading } from '@element-plus/icons-vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'

const authStore = useAuthStore()
const router = useRouter()
const menuOpen = ref(false)
const isLoading = ref(true)

// 计算当前日期
const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long',
    hour: '2-digit',
    minute: '2-digit'
  })
})

// 组件是否准备就绪
const isReady = computed(() => {
  return authStore.isAuthenticated && authStore.user
})

// 切换菜单
const toggleMenu = () => {
  menuOpen.value = !menuOpen.value
}

// 登出处理
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const loading = ElLoading.service({
      lock: true,
      text: '正在退出...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      await authStore.logout()
      loading.close()
      ElMessage.success('已安全退出')
      await router.push('/login')
    } catch (error) {
      loading.close()
      ElMessage.error('退出失败: ' + (error.message || '未知错误'))
    }
  } catch (error) {
    // 用户取消操作
    console.log('用户取消退出')
  }
};

// 组件挂载时检查认证状态
onMounted(async () => {
  try {
    // 确保认证状态已初始化
    if (!authStore.isInitialized) {
      await authStore.initialize()
    }

    // 如果未认证，跳转到登录页
    if (!authStore.isAuthenticated) {
      router.push('/login')
    }
  } catch (error) {
    console.error('初始化失败:', error)
    router.push('/login')
  } finally {
    isLoading.value = false
  }
})
</script>

<style scoped>
/* 保持原有样式不变 */
.dashboard {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f4f7fb;
  font-family: 'Arial', sans-serif;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  font-size: clamp(1.25rem, 3vw, 1.75rem);
  font-weight: 700;
  color: #2d3748;
  margin: 0;
}

.user-menu {
  position: relative;
}

.user-button {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.75rem 1.25rem;
  border-radius: 8px;
  transition: all 0.3s ease;
  color: #4a5568;
  font-weight: 600;
}

.user-button:hover {
  background-color: #f0f4f8;
}

.user-avatar {
  width: clamp(28px, 5vw, 36px);
  height: clamp(28px, 5vw, 36px);
  border-radius: 50%;
  margin-right: 0.75rem;
  object-fit: cover;
}

.user-name {
  font-weight: 600;
  color: #2d3748;
  margin-right: 0.5rem;
}

.dropdown-menu {
  position: absolute;
  right: 0;
  top: 100%;
  margin-top: 0.5rem;
  min-width: 200px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 20;
  overflow: hidden;
  pointer-events: none;
}

.dropdown-menu.opacity-100 {
  pointer-events: auto;
}

.dropdown-item {
  display: flex;
  align-items: center;
  padding: 0.75rem 1rem;
  width: 100%;
  text-align: left;
  background: none;
  border: none;
  color: #4a5568;
  cursor: pointer;
  transition: all 0.2s ease;
}

.dropdown-item i {
  margin-right: 0.75rem;
  width: 20px;
  text-align: center;
}

.dropdown-item:hover {
  background-color: #f7fafc;
  color: #2d3748;
  transform: translateX(5px);
}

.dropdown-divider {
  height: 1px;
  background-color: #e2e8f0;
  margin: 0.25rem 0;
}

.dashboard-content {
  flex: 1;
  padding: clamp(1rem, 3vw, 2rem);
  background: #f4f7fb;
}

.welcome-card {
  display: flex;
  flex-direction: column-reverse;
  justify-content: space-between;
  align-items: center;
  border-radius: 16px;
  padding: clamp(1.5rem, 3vw, 2rem);
  color: white;
  margin-bottom: 2rem;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  text-align: center;
}

@media (min-width: 768px) {
  .welcome-card {
    flex-direction: row;
    text-align: left;
  }
}

.welcome-card:hover {
  transform: translateY(-5px);
}

.welcome-text h2 {
  font-size: clamp(1.5rem, 3vw, 2rem);
  font-weight: 700;
  margin: 0 0 0.5rem 0;
}

.welcome-text p {
  font-size: clamp(1rem, 2vw, 1.1rem);
  opacity: 0.9;
  margin: 0;
}

.welcome-image img {
  height: clamp(5rem, 15vw, 8rem);
  max-width: 100%;
  margin-bottom: 1rem;
}

@media (min-width: 768px) {
  .welcome-image img {
    margin-bottom: 0;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  gap: 10px;
  font-size: 1.2rem;
  color: #409EFF;
}

.is-loading {
  animation: rotating 2s linear infinite;
  font-size: 24px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>